import glob, os, sys

#
# WARNING:
# Always run on a copy of your files!! The renaming cannot be undone automatically!
#

def run(path="./", test = False, log = True, ext = ".png"):

    dirs = [f for f in os.listdir(path)
        if not os.path.isfile(os.path.join(path, f))]

    if log:
        logfile = open(path + "filenames.txt","w")
    else:
        logfile = None
    
    for direc in dirs:
        ren_dir_files(direc, path, logfile, test, ext)
    
    if log:
        logfile.close()


def ren_dir_files(direc, basepath, logfile, test, ext = ".png"):
    if basepath[-1:] not in "/\\" and os.path.isdir(basepath):
        basepath += "/"
    path = basepath + direc + "/"

    len_path = len(path)

    if logfile is not None:
        logfile.write("\n"+direc+"\n")

    i = 1
    for filename in glob.glob(path + "*" + ext):
        i_str = ""
        if i <= 9:
            i_str += "0" + str(i)
        else:
            i_str = str(i)
        new_name = "p" + direc + "_" + i_str + "_01"
        new_name_ext = new_name + ext
        print filename[len_path:] + " ==> " + new_name_ext

        if not test:
            if not (filename[len_path:] == new_name_ext):
                if os.path.exists(path + new_name_ext):
                    os.remove(path + new_name_ext)
                os.rename(filename, path + new_name_ext)
        
        if logfile is not None:
            new_name_02 = new_name[:-1] + "2"
            logfile.write(new_name + "\t" + new_name_02 + "\n")
        i += 1
    print "\nrenamed {0} files in directory {1}\n".format(i - 1, direc)

def main():
    if (len(sys.argv) > 1):
        if( sys.argv[1] == 'test' ):
            if (sys.argv > 2):
                run(test = True, ext = sys.argv[2])
            else:
                run(test = True)
        elif( sys.argv[1] == 'run' ):
            if (sys.argv > 2):
                run(ext = sys.argv[2])
            else:
                run()
        else:
            print "Please call with either of these parameters and optional file extension (default: '.png'):"
            print "'test' or 'run'"
            
    
main()
